package leetcode.f1t100;

import leetcode.struct.TreeNode;

import java.util.Stack;

/**
 * 校验是否搜索二叉树
 * https://leetcode.com/problems/validate-binary-search-tree
 *
 * @author lichx
 * @createTime 2024/2/21 16:10
 */
public class Q98_ValidateBinarySearchTree {

    public static void main(String[] args) {
        Q98_ValidateBinarySearchTree bean = new Q98_ValidateBinarySearchTree();
        System.out.println(bean.isValidBST(new TreeNode(2, new TreeNode(2), new TreeNode(2))));
    }

    public boolean isValidBST(TreeNode root) {
//        return isValidBSTRecursion(root, Long.MIN_VALUE, Long.MAX_VALUE);
        return isValidBSTNotRecursion(root);
    }

    private boolean isValidBSTRecursion(TreeNode root, long min, long max) {
        if (root == null) {
            return true;
        }
        if (root.val <= min || root.val >= max) {
            return false;
        }
        return isValidBSTRecursion(root.left, min, root.val) && isValidBSTRecursion(root.right, root.val, max);
    }

    private boolean isValidBSTNotRecursion(TreeNode root) {
        if (root == null) {
            return true;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if(pre != null && pre.val >= root.val) {
                return false;
            }
            pre = root;
            root = root.right;
        }
        return true;
    }

}
